package com.itheima.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.activemq.network.jms.JmsQueueConnector;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.itheima.bos.utils.MailUtils;

import cn.itcast.crm.domain.Customer;

@Namespace("/")
@ParentPackage("json-default")
@Actions
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {

	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	@Action(value = "sendVerifyCode")
	public String sendVerifyCode() throws Exception {
		// 手机保存Customer对象
		// 生成短信验证码
		String randomCode = RandomStringUtils.randomNumeric(4);
		// 将生成的验证码存储到Session中
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		// 编辑短信内容
		final String msg = "尊敬的用户您好，本次获取的验证码为：" + randomCode + ",服务电话：4006184000";
		// 调用MQ发送消息
		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage createMapMessage = session.createMapMessage();
				createMapMessage.setString("telephone", model.getTelephone());
				createMapMessage.setString("msg", msg);
				return createMapMessage;
			}
		});

		return NONE;
	}

	private String checkCode;

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	/***
	 * 注册客户信息
	 */
	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "error", type = "redirect", location = "signup.html") })
	public String customerRegist() {
		// 判断验证码
		String checkCodeSession = (String) ServletActionContext.getRequest().getSession()
				.getAttribute(model.getTelephone());
		if (checkCodeSession == null || !checkCodeSession.equals(checkCode)) {
			// 验证码错误
			return ERROR;
		}
		// 调用WEBSERVICE 连接CRM 保存客户信息
		WebClient.create("http://localhost:9002").path("crm_management").path("services").path("customerService")
				.path("customer").type(MediaType.APPLICATION_JSON).post(model);

		// 发送一封激活邮件
		// 生成激活码
		String randomNumeric = RandomStringUtils.randomNumeric(32);
		// 将激活码保存到redis,设置24小时失效
		redisTemplate.opsForValue().set(model.getTelephone(), randomNumeric, 24, TimeUnit.HOURS);
		// 调用MailUtils发送激活邮件
		String content = "尊敬的客户你好,请于24小时内,进行邮箱账户的绑定,点击下面地址完成绑定:<br/>" + "<a href='" + MailUtils.activeUrl
				+ "?telephone=" + model.getTelephone() + "&activecode=" + randomNumeric + "'>速运快递绑定邮箱地址</a>";
		MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());
		return SUCCESS;

	}

	/***
	 * 绑定邮箱
	 */
	// 属性驱动
	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action("customer_activeMail")
	public String activeMail() throws IOException {
		// 判断验证码是否有效
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		String activeCodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
		if (activeCodeRedis == null || activeCodeRedis.equals(activecode)) {
			// 激活码无效
			ServletActionContext.getResponse().getWriter().println("激活码无效请重新绑定");
		} else {
			// 激活码有效
			// 防止重复绑定
			Customer customer = WebClient.create("http://localhost:9002").path("crm_management").path("services")
					.path("customerService").path("customer").path("telephone").query("telephone", model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if (customer.getType() != 1) {
				// 说明没有绑定
				WebClient.create("http://localhost:9002").path("crm_management").path("services")
						.path("customerService").path("customer").path("update")
						.query("telephone", model.getTelephone()).put(Customer.class);
				ServletActionContext.getResponse().getWriter().println("绑定成功");
			} else {
				// 已经绑定
				ServletActionContext.getResponse().getWriter().println("请勿重复绑定");
			}
			redisTemplate.delete(model.getTelephone());
		}

		return NONE;
	}

	/***
	 * 登录账号
	 */

	@Action(value = "customer_login", results = { @Result(name = "login", location = "login.html", type = "redirect"),
			@Result(name = "success", type = "redirect", location = "index.html#/myhome") })
	public String customer_login() {
		
		  Customer customer = WebClient.create("http://localhost:9002")
		  .path("crm_management")
		  .path("services")
		  .path("customerService")
		  .path("customer_login")
		  .query("telephone", model.getTelephone())
		  .query("password", model.getPassword())
		  .accept(MediaType.APPLICATION_JSON)
		  .get(Customer.class);
		  
		  if(customer==null){
			  //用户不存在
			  return LOGIN;
		  }else{
			  //将用户存在Session中
			  ServletActionContext.getRequest().getSession().setAttribute("customer",customer);
			  return SUCCESS;
		  }
		
		
	}

}
